package tushare

import (
	"bytes"
	"fmt"
	"strings"
	"time"
	"tushare/model"

	"strconv"

	"net/http"

	"github.com/PuerkitoBio/goquery"
)

func SpiderStock(i int64) {
	for {
		spiderStockSend(i)
		time.Sleep(time.Second * 1)
	}
}

/*
根据类型进行爬取
*/
func SpiderStockByType(typeStr string) {
	//收藏
	if typeStr == "collect" {
		stock := model.StockListCollect()
		var buffer bytes.Buffer
		for _, v := range stock {
			tsCodeArr := strings.Split(v.TsCode, ".")
			if tsCodeArr[1] != "SH" && tsCodeArr[1] != "SZ" {
				continue
			}
			url := "https://xueqiu.com/S/" + tsCodeArr[1] + tsCodeArr[0]
			_ = getNowPrice(url, v.TsCode, buffer)
		}
	}
}

func spiderStockSend(i int64) {
	var buffer bytes.Buffer
	stock := model.StockListSimpPage(i, 1000)
	// stockLen := len(stock)
	for _, v := range stock {
		tsCodeArr := strings.Split(v.TsCode, ".")
		if tsCodeArr[1] != "SH" && tsCodeArr[1] != "SZ" {
			continue
		}
		url := "https://xueqiu.com/S/" + tsCodeArr[1] + tsCodeArr[0]
		_ = getNowPrice(url, v.TsCode, buffer)
		time.Sleep(time.Millisecond * 2)
	}
}

func getNowPrice(url string, tsCode string, buffer bytes.Buffer) string {
	var sql string
	res, err := http.Get(url)
	if err != nil {
		//fmt.Println(err)
		return ""
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		//fmt.Println("网络未正常响应httpCode:")
		//fmt.Println(res.StatusCode)
		return ""
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)

	if err != nil {
		// fmt.Println(err)
		return ""
	}

	sql = "UPDATE tushare_stock "

	doc.Find(".stock-current").Each(func(i int, s *goquery.Selection) {
		text := s.Find("strong").Text()
		price := strings.TrimLeft(text, "¥")
		sql = fmt.Sprintf("%s SET close='%s' ", sql, price)
	})

	doc.Find(".stock-change").Each(func(i int, s *goquery.Selection) {
		change := s.Text()
		//fmt.Println(change)
		changeArr := strings.Split(change, " ")
		a, _ := strconv.ParseFloat(changeArr[0], 64)
		// ts := model.TushareStock{}
		// ts.ImAmount = a
		// fmt.Println(ts.ImAmount)
		// model.StockUpdate(tsCode, ts)

		sql = fmt.Sprintf("%s , im_amount='%f' WHERE ts_code='%s';", sql, a, tsCode)
	})
	model.StockExec(sql)
	return sql
}
